﻿// ----------------------------------------------------------------------
// <copyright file="SystemEventLogger.cs" company="Euroland.com">
//     Copyright (c) Euroland.com. All rights reserved.
// </copyright>
// <author>binh.nguyen@euroland.com</author>
// <created>Monday, April 09, 2012 11:41</created>
// <lastedit>Monday, April 09, 2012 11:41</lastedit>
// <changes>
// </changes>
// -----------------------------------------------------------------------
using System;

namespace Southern.Common.Logger
{
    /// <summary>
    /// A logger class to log event information into System Event Log.
    /// To view the exceptions, using Event Viewer of Windows
    /// </summary>
    public sealed class SystemEventLogger: ILogger
    {
        private System.Diagnostics.EventLog systemEventLog;
        private const string EUROLAND_TOOLS_LOG_NAME = "ErrorlandTools";

        public string ApplicationName
        {
            get;
            private set;
        }

        public SystemEventLogger(string applicationName)
        {
            if (!string.IsNullOrEmpty(applicationName))
                this.ApplicationName = applicationName;
            else
                this.ApplicationName = EUROLAND_TOOLS_LOG_NAME;
            systemEventLog = new System.Diagnostics.EventLog("Application");
            systemEventLog.Source = this.ApplicationName;
            systemEventLog.MachineName = ".";
        }

        #region ILogger Members

        public void Log(string message)
        {
            this.WriteLog(message);
        }

        public void Log(string[] categories, string message)
        {
            this.WriteLog(message);
        }

        public void LogException(Exception x)
        {
            this.WriteLog(x.ToString());
        }
        #endregion

        private void WriteLog(string errorMsg)
        {
            try
            {
                systemEventLog.WriteEntry(errorMsg, System.Diagnostics.EventLogEntryType.Error);
            }
            catch { }
            finally
            {
                systemEventLog.Close();
            }
        }
    }
}
